<!-- pages/order/my-orders.vue -->
<template>
	<view class="container">
		<!-- 订单类型选项卡 -->
		<view class="tab-bar">
			<view v-for="(tab, index) in tabs" :key="index"
				:class="['tab-item', currentTab === index ? 'tab-active' : '']" @tap="switchTab(index)">
				{{ tab.name }}
			</view>
		</view>

		<!-- 搜索框 -->
		<view class="search-box">
			<view class="search-input">
				<text class="iconfont icon-search">🔍</text>
				<input type="text" v-model="keyword" placeholder="搜索订单号/婴儿车编号" confirm-type="search"
					@confirm="searchOrders" />
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view scroll-y class="order-list" @scrolltolower="getOrderLists" v-if="orderList.length > 0">
			<view class="order-item" v-for="(order, index) in orderList" :key="index" @tap="viewOrderDetail(order)">
				<!-- 订单头部 -->
				<view class="order-header">
					<view class="order-number">订单号：{{ order.order_id }}</view>
					<view :class="['order-status', getStatusClass(order.status)]">{{ getStatusText(order.status) }}
					</view>
				</view>

				<!-- 订单内容 -->
				<view class="order-content">
					<view class="stroller-image">
						<image src="/static/images/stroller.png" mode="aspectFill"></image>
					</view>
					<view class="order-info">
						<view class="stroller-name">共享婴儿车</view>
						<view class="stroller-id">婴儿车编号：{{ order.wheel_hw_code }}</view>
						<view class="use-time">使用时间：{{ formatTime(order.start_time) }}至{{ formatTime(order.end_time) }}
						</view>
						<view class="station-name">借车点：{{ order.station.title }}</view>
					</view>
				</view>

				<!-- 订单底部 -->
				<view class="order-footer">
					<view class="order-price">
						<text>实付：</text>
						<text class="price">¥{{ parseFloat(order.final_fee).toFixed(2) }}</text>
					</view>
					<view class="order-buttons">
						<view class="btn btn-plain" v-if="order.status === 'unpaid'" @tap.stop="deleteOrder(order)">删除订单</view>
						<!-- <view class="btn btn-primary" v-if="order.status === 'paid'" @tap.stop="pauseOrder(order)">暂停订单
						</view>
						<view class="btn btn-primary" v-if="order.status === 'paid'" @tap.stop="endOrder(order)">结束订单
						</view> -->
						<view class="btn btn-plain" v-if="order.status === 'completed'" @tap.stop="viewReturnDetail(order)">查看详情
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view class="load-more" v-if="hasMoreOrders">
				<text>加载中...</text>
			</view>
			<view class="load-more" v-else>
				<text>没有更多订单了</text>
			</view>
		</scroll-view>

		<!-- 空订单提示 -->
		<view class="empty-tip" v-else>
			<image class="empty-image" src="/static/images/empty-order.png"></image>
			<text class="empty-text">暂无订单</text>
		</view>
		<uni-popup ref="settlePopup" type="dialog">
			<view class="popup-content">
				<view class="popup-title">确认结算</view>
				<view class="popup-message">是否确认结算此订单？</view>
				<view class="popup-amount">订单结束时间：<uni-datetime-picker type="datetime" v-model="end_time" placeholder="默认当前时间" :start="currentOrder.start_time"/></view>
				<view class="popup-buttons">
					<view class="popup-btn popup-btn-cancel" @tap="closeSettlePopup">取消</view>
					<view class="popup-btn popup-btn-confirm" @tap="handleSettlement">确认</view>
				</view>
			</view>
		</uni-popup>
		
		<!-- 结算成功弹窗 -->
		<uni-popup ref="successPopup" type="dialog">
			<view class="popup-content">
				<view class="popup-title">结算成功</view>
				<view class="success-icon">✓</view>
				<view class="popup-message">订单已成功结算</view>
				<!-- <view class="popup-amount">结算金额：<text class="popup-price">¥{{ totalFee.toFixed(2) }}</text></view> -->
				<view class="popup-buttons">
					<view class="popup-btn popup-btn-confirm" @tap="closeSuccessPopup">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {endOrderApi, getOrderList} from '@/api/order.js'
	export default {
		data() {
			return {
				// 标签页配置
				tabs: [{
						name: '全部',
						status: 'all'
					},
					{
						name: '使用中',
						status: 'using'
					},
					{
						name: '已完成',
						status: 'completed'
					},
					{
						name: '已取消',
						status: 'unpaid'
					}
				],
				currentTab: 0,
				totalFee: 0,
				// 搜索关键词
				keyword: '',

				// 订单列表
				orderList: [],
				fullOrderList: [], // 保存完整的订单列表用于搜索

				// 分页
				page: 1,
				pageSize: 20,
				hasMoreOrders: true,

				// 当前操作的订单
				currentOrder: null,
				end_time:"",
			};
		},
		onLoad() {
			this.getOrderLists();
		},
		methods: {
			// 切换标签页
			switchTab(index) {
				if (this.currentTab === index) return;
				this.currentTab = index;
				this.orderList = [];
				this.page = 1;
				this.hasMoreOrders = true;
				this.getOrderLists();
			},
			
			// 根据当前标签过滤订单
			filterOrders() {
				if (this.currentTab === 0) {
					// 全部订单
					this.orderList = [...this.fullOrderList];
				} else {
					// 根据状态过滤
					const status = this.tabs[this.currentTab].status;
					this.orderList = this.fullOrderList.filter(order => order.status === status);
				}
			},

			// 获取订单列表
			async getOrderLists() {
				if(!this.hasMoreOrders){
					console.log("没有了")
					return
				}
				try {
					const keyword = this.keyword.trim().toLowerCase();
					const status = this.tabs[this.currentTab].status;
					let res = await getOrderList({
						keyword:keyword,
						status:status,
						page:this.page,
						limit:this.pageSize
					});
					if (res.code === 200) {
						// 处理接口返回的真实数据
						let lists = res.data.data
						this.fullOrderList = lists.map(order => {
							return {
								...order,
								// 添加前端需要的字段
								strollerImage: '/static/images/stroller.png',
								strollerName: '共享婴儿车',
								stationName: order.station.title
							}
						});
						this.orderList = [...this.orderList,...this.fullOrderList]
						this.hasMoreOrders = res.data.has_more
						this.page++
						//this.filterOrders();
					} else {
						uni.showToast({
							title: res.message || '获取订单失败',
							icon: 'none'
						});
					}
				} catch (e) {
					console.error('获取订单列表失败', e);
					uni.showToast({
						title: '获取订单失败',
						icon: 'none'
					});
				}
			},

			// 加载更多订单
			loadMoreOrders() {
				if (!this.hasMoreOrders) return;
				// 真实接口可能需要分页参数
				// 这里简单处理，一次加载所有数据
				this.hasMoreOrders = false;
			},

			// 搜索订单
			searchOrders() {
				this.orderList = [];
				this.page = 1;
				this.hasMoreOrders = true;
				return this.getOrderLists();
				/*if (!this.keyword.trim()) {
					this.filterOrders();
					return;
				}

				const keyword = this.keyword.trim().toLowerCase();
				this.orderList = this.fullOrderList.filter(order => {
					return order.order_id.toLowerCase().includes(keyword) || 
						   order.wheel_hw_code.toLowerCase().includes(keyword);
				});*/
			},

			// 查看订单详情
			viewOrderDetail(order) {
				uni.navigateTo({
					url: `/pages/order/detail?id=${order.order_id}`
				});
			},

			// 扫码还车
			scanToReturn(order) {
				uni.scanCode({
					success: () => {
						uni.navigateTo({
							url: `/pages/order/return?id=${order.order_id}`
						});
					},
					fail: () => {
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						});
					}
				});
			},

			// 查看归还详情
			viewReturnDetail(order) {
				uni.navigateTo({
					url: `/pages/order/return-detail?id=${order.order_id}`
				});
			},

			// 删除订单
			deleteOrder(order) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该订单吗？',
					success: (res) => {
						if (res.confirm) {
							// 执行删除操作
							this.orderList = this.orderList.filter(item => item.order_id !== order.order_id);
							this.fullOrderList = this.fullOrderList.filter(item => item.order_id !== order.order_id);

							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						}
					}
				});
			},

			// 再次租用
			rentAgain(order) {
				uni.navigateTo({
					url: `/pages/rent/index?strollerId=${order.wheel_hw_code}`
				});
			},

			// 去租用婴儿车
			goToRent() {
				uni.switchTab({
					url: '/pages/home/index'
				});
			},

			// 获取状态文本
			getStatusText(status) {
				// 根据新规则映射状态
				if (status === 'unpaid') {
					return '已取消';
				} else if (status === 'completed') {
					return '已完成';
				} else {
					return '使用中';
				}
			},

			// 获取状态样式类
			getStatusClass(status) {
				// 根据新规则设置样式类
				if (status === 'unpaid') {
					return 'status-canceled';
				} else if (status === 'completed') {
					return 'status-completed';
				} else {
					return 'status-using';
				}
			},

			// 格式化时间
			formatTime(timeStr) {
				if (!timeStr) return '';

				// 将 "2025-05-19 16:51:36" 格式化为 "05-19 16:51"
				let timearr = timeStr.split("-")
				return `${timearr[1]}-${timearr[2]}`;
				/*const date = new Date(timeStr);
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				
				return `${month}-${day} ${hours}:${minutes}`;*/
				
			},
			endOrder(order){
				this.currentOrder = order
				this.$refs.settlePopup.open();
			},
			// 处理结算
			handleSettlement() {
				if(this.end_time<this.currentOrder.start_time){
					return uni.showToast({
						icon:"error",
						title:"结束时间不能早于开始时间"
					})
				}
				uni.showLoading({
					title: '结算中...'
				});
				endOrderApi({
					order_id:this.currentOrder.order_id,
					end_time:this.end_time
				}).then((res)=>{
					uni.hideLoading();
					this.closeSettlePopup();
					this.showSuccessPopup();
					this.orderList = [];
					this.page = 1;
					this.hasMoreOrders = true;
					this.getOrderLists();
				})
			},
			// 关闭结算确认弹窗
			closeSettlePopup() {
				this.$refs.settlePopup.close();
			},
			// 显示结算成功弹窗
			showSuccessPopup() {
				this.$refs.successPopup.open();
			},
			// 关闭结算成功弹窗
			closeSuccessPopup() {
				this.$refs.successPopup.close();
			},
		}
	};
</script>

<style>
	/* 美团风格 - 黄色主色调 #FFD100 */
	.container {
		background-color: #F5F5F5;
		min-height: 100vh;
	}

	/* 导航栏 */
	.nav-bar {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0 30rpx;
		height: 90rpx;
		background-color: #FFFFFF;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.nav-title {
		font-size: 34rpx;
		font-weight: bold;
		color: #333333;
	}

	/* 标签栏 */
	.tab-bar {
		display: flex;
		background-color: #FFFFFF;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.tab-item {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 28rpx;
		color: #666666;
		position: relative;
	}

	.tab-active {
		color: #FFD100;
		font-weight: bold;
	}

	.tab-active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background-color: #FFD100;
		border-radius: 2rpx;
	}

	/* 搜索框 */
	.search-box {
		padding: 20rpx 30rpx;
		background-color: #FFFFFF;
	}

	.search-input {
		display: flex;
		align-items: center;
		height: 70rpx;
		background-color: #F5F5F5;
		border-radius: 35rpx;
		padding: 0 30rpx;
	}

	.icon-search {
		font-size: 28rpx;
		color: #999999;
		margin-right: 10rpx;
	}

	/* 订单列表 */
	.order-list {
		height: calc(100vh - 280rpx);
		padding-bottom: 30rpx;
	}

	.order-item {
		margin: 20rpx 30rpx 0;
		background-color: #FFFFFF;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	/* 订单头部 */
	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #F5F5F5;
	}

	.order-number {
		font-size: 26rpx;
		color: #666666;
	}

	.order-status {
		font-size: 26rpx;
		font-weight: bold;
	}

	.status-canceled {
		color: #9E9E9E;
	}

	.status-completed {
		color: #4CAF50;
	}

	.status-using {
		color: #2196F3;
	}

	/* 订单内容 */
	.order-content {
		display: flex;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #F5F5F5;
	}

	.stroller-image {
		width: 160rpx;
		height: 160rpx;
		margin-right: 20rpx;
		border-radius: 8rpx;
		overflow: hidden;
	}

	.stroller-image image {
		width: 100%;
		height: 100%;
	}

	.order-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.stroller-name {
		font-size: 30rpx;
		color: #333333;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.stroller-id,
	.use-time,
	.station-name {
		font-size: 24rpx;
		color: #999999;
		margin-bottom: 10rpx;
	}

	/* 订单底部 */
	.order-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
	}

	.order-price {
		font-size: 26rpx;
		color: #666666;
	}

	.price {
		font-size: 32rpx;
		color: #FF5722;
		font-weight: bold;
	}

	.order-buttons {
		display: flex;
		align-items: center;
	}

	.btn {
		margin-left: 20rpx;
		padding: 10rpx 20rpx;
		border-radius: 30rpx;
		font-size: 24rpx;
	}

	.btn-primary {
		background-color: #FFD100;
		color: #333333;
	}

	.btn-plain {
		background-color: #FFFFFF;
		color: #666666;
		border: 1rpx solid #DDDDDD;
	}

	.btn-large {
		padding: 15rpx 40rpx;
		font-size: 28rpx;
		margin-top: 30rpx;
	}

	/* 加载更多 */
	.load-more {
		text-align: center;
		padding: 30rpx 0;
		font-size: 24rpx;
		color: #999999;
	}

	/* 空数据提示 */
	.empty-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 30rpx;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999999;
		margin-bottom: 30rpx;
	}
	/* 弹窗样式 */
	.popup-content {
		background-color: #FFFFFF;
		border-radius: 12rpx;
		padding: 30rpx;
		width: 80vw;
	}
	
	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		text-align: center;
		margin-bottom: 30rpx;
	}
	
	.popup-message {
		font-size: 28rpx;
		color: #666666;
		text-align: center;
		margin-bottom: 20rpx;
	}
	
	.popup-amount {
		font-size: 28rpx;
		color: #666666;
		text-align: center;
		margin-bottom: 30rpx;
	}
	
	.popup-price {
		font-size: 36rpx;
		font-weight: bold;
		color: #FF5722;
	}
	
	.popup-buttons {
		display: flex;
		justify-content: space-around;
	}
	
	.popup-btn {
		width: 48%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 40rpx;
		font-size: 28rpx;
	}
	
	.popup-btn-cancel {
		background-color: #F5F5F5;
		color: #666666;
	}
	
	.popup-btn-confirm {
		background-color: #FFD100;
		color: #333333;
	}
	
	.success-icon {
		width: 120rpx;
		height: 120rpx;
		line-height: 120rpx;
		text-align: center;
		font-size: 60rpx;
		color: #FFFFFF;
		background-color: #4CAF50;
		border-radius: 50%;
		margin: 0 auto 30rpx;
	}
</style>